__author__ = 'Johnny'
# coding: utf-8

from django.views.generic import TemplateView
from django.http.response import HttpResponse
from weixin.form.form import *
import json
import hashlib



WEIXIN_TOKEN = 'asdasfdewgfwgwq2425'

def response(code, data):
    ret = {
        'code': code,
        'message': '',
        'data': data
    }
    resp = HttpResponse(json.dumps(ret),
                        content_type='application/json',
                        status=200)
    return resp


class BaseView(TemplateView):
    template_name = 'wssa/base_view.html'


class Weixin(BaseView):
    def get(self, request, *args, **kwargs):
        weixin_form = WeixinForm(request.GET)
        if not weixin_form.is_valid():
            return response(302, '')
        signature = weixin_form.cleaned_data['signature']
        timestamp = weixin_form.cleaned_data['timestamp']
        nonce = weixin_form.cleaned_data['nonce']
        echostr = weixin_form.cleaned_data['echostr']

        token = WEIXIN_TOKEN
        tmp_list = [token, timestamp, nonce]
        tmp_list.sort()
        tmp_str = "%s%s%s" % tuple(tmp_list)
        tmp_str = hashlib.sha1(tmp_str).hexdigest()
        if tmp_str == signature:
            return HttpResponse(echostr)
        else:
            return HttpResponse("weixin  index")

        # return response(0, 'ok')


